const express = require('express');
//引入连接池模块
const pool = require('../pool.js');
//创建路由器对象
const r = express.Router();
r.get('/addorder', (req, res) => {
  //1.1获取post请求的数据
  var obj = req.query;
  //1.2验证各项数据是否为空
  var i = 400;
  for (var k in obj) {
    i++;
    if (!obj[k]) {
      res.send({ code: i, msg: k + '不能为空' });
      return;
    }
  }
  //1.3执行SQL命令，将数据插入到数据表
  pool.query('insert into order_table set ?', [obj], (err, result) => {
    if (err) {
      console.log(err);
      res.send({ code: 500, msg: '服务器端错误' });
      return;
    }
    res.send({ code: 200, msg: '订单添加成功' });
  });
});
//2.订单列表(get /)
r.get('/orderlist', (req, res) => {
  //2.1获取查询字符串传递的数据
  var obj = req.query;
  var uid = req.query.uid;
  //1.2验证是否为空
  if (!obj.pno) obj.pno = 1;
  if (!obj.count) obj.count = 15;
  //2.3计算开始查询的值
  var start = (obj.pno - 1) * obj.count;
  //2.4将每页的数据量强制转为整型
  var size = parseInt(obj.count);
  //2.5执行SQL命令
  pool.query('select * from order_table where uid =?  limit ?,?', [uid, start, size], (err, result) => {
    if (err) {
      console.log(err);
      res.send({ code: 500, msg: '服务器端错误' });
      return;
    }
    res.send({ code: 200, msg: '查询成功', data: result });
  });
});
// 3.根据订单id查询订单详情
r.get("/orderdetail/:id", (req, res) => {
  //2.1获取查询字符串传递的数据
  var obj = req.query;
  var id = req.params.id;
  console.log(id);

  //2.5执行SQL命令
  pool.query('select * from order_table where id = ?', [id], (err, result) => {
    if (err) {
      console.log(err);
      res.send({ code: 500, msg: '服务器端错误' });
      return;
    }
    res.send({ code: 200, msg: '查询成功', data: result });
  });
})
//导出路由器对象
module.exports = r;